﻿using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.Extensions.Configuration;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Transactions;
using System.Xml;
using System.Xml.Linq;
using WCS.Infrastructure.Attr;
using WCS.Infrastructure.Dto.Enums;
using WCS.Infrastructure.Dto.Request.Epaylinks;
using WCS.Infrastructure.Dto.Request.Organization;
using WCS.Infrastructure.Dto.Response.Common;
using WCS.Infrastructure.Dto.Response.Epaylinks;
using WCS.Infrastructure.Dto.Response.Organization;
using WCS.Infrastructure.Dto.Response.User;
using WCS.Infrastructure.EFCore;
using WCS.Infrastructure.IOC;
using WCS.Infrastructure.Tools;
using WCS.Repository.Interface;
using WCS.Service.Interface;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;
using static System.Formats.Asn1.AsnWriter;

namespace WCS.Service.Instance
{
    [Inject]
    public class OrganizationService : BaseService, IOrganizationService
    {
        private readonly IConfiguration _configuration;
        private readonly OrganizationIOC _orgIOC;
        private readonly IUserService _userService;
        private readonly IPaymentCodeService _paymentCodeService;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ILogService _logService;
        EpaylinksService epaylinksService = null;
        private readonly ISmsService _smsService;
        private readonly IUnitOfWork _unitOfWork;
        public OrganizationService(IConfiguration configuration, OrganizationIOC organizationIOC, IUserService userService, IPaymentCodeService paymentCodeService,
            IHttpContextAccessor httpContextAccessor, ILogService logService, ISmsService smsService, IUnitOfWork unitOfWork)
        {
            _configuration = configuration;
            _orgIOC = organizationIOC;
            _userService = userService;
            _paymentCodeService = paymentCodeService;
            _httpContextAccessor = httpContextAccessor;
            epaylinksService = new EpaylinksService(_configuration, _httpContextAccessor);
            _logService = logService;
            _smsService = smsService;
            _unitOfWork = unitOfWork;
        }

        /// <summary>
        /// 新增角色
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> AddRoleAsync(RoleRequestDto dto)
        {
            SysRole sysRole = new SysRole()
            {
                Id = Config.GUID(),
                RoleName = dto.RoleName,
                OrganizationType = dto.OrganizationType,
                RoleType = (int)dto.RoleType,
                Description = dto.Description,
                CreationTime = DateTime.Now,
            };
            await _orgIOC._sysRoleEFCore.AddAsync(sysRole);
            var result = await _orgIOC._sysRoleEFCore.SaveChangesAsync();
            return GetResult(result);
        }

        /// <summary>
        /// 删除角色（批量）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> DeleteRoleAsync(RoleRequestDto dto)
        {
            var iq = _orgIOC._sysRoleEFCore.QueryAll(d => dto.Ids.Contains(d.Id));
            if (!await iq.AnyAsync())
            {
                return GetResult(message: "参数错误");
            }
            await _orgIOC._sysRoleEFCore.DeleteRangeAsync(iq);
            var result = await _orgIOC._sysRoleEFCore.SaveChangesAsync();
            return GetResult(result);
        }

        /// <summary>
        /// 编辑系统角色
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> UpdateRoleAsync(RoleRequestDto dto)
        {
            var role = await _orgIOC._sysRoleEFCore.QueryAll(d => d.Id == dto.Id).FirstOrDefaultAsync();
            if (role == null)
            {
                return GetResult(message: "参数错误");
            }

            role.RoleName = dto.RoleName;
            role.RoleType = (int)dto.RoleType;
            role.Description = dto.Description;
            role.OrganizationType = dto.OrganizationType;
            await _orgIOC._sysRoleEFCore.UpdateAsync(role);
            var result = await _orgIOC._sysRoleEFCore.SaveChangesAsync();
            return GetResult(result);
        }

        /// <summary>
        /// 获取系统角色列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetRoleListAsync(RoleRequestDto dto)
        {
            var data = await _orgIOC._sysRoleEFCore.QueryAll(d => (string.IsNullOrEmpty(dto.RoleName) || d.RoleName.Contains(dto.RoleName))
                && (dto.OrgTypeList == null || dto.OrgTypeList.Contains((int)d.OrganizationType)),
                d => d.CreationTime, true).Select(d => new RoleRequestDto
                {
                    Id = d.Id,
                    RoleName = d.RoleName,
                    RoleType = d.RoleType,
                    OrganizationType = d.OrganizationType,
                    Description = d.Description,
                    CreationTime = d.CreationTime,
                }).ToListAsync();

            return GetResult(1, data: data);

        }

        /// <summary>
        /// 获取用户角色商户列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetUserRoleMerchantListAsync(string? userId)
        {
            if (string.IsNullOrEmpty(userId))
            {
                 userId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
            }
            var user = await _orgIOC._sysUserEFCore.QueryAll(d => d.Id == userId).FirstOrDefaultAsync();
            var data = await _orgIOC._sysUserRoleEFCore.QueryAll(d => d.UserId == user.Id,
                d => d.CreationTime, false).Select(d => new UserRoleRequestDto
                {
                    Id = d.Id,
                    UserId = d.UserId,
                    RoleId = d.RoleId,
                    MerchantId = d.MerchantId,
                    StoreId = d.StoreId,
                    Name = d.Name,
                    UserPhone = user.Phone,
                    CreationTime = d.CreationTime,
                    CreatorId = d.CreatorId,
                    IsDeleted = d.IsDeleted,
                    EnableStatus = d.EnableStatus,
                }).ToListAsync();

            data = data.DistinctBy(d => d.MerchantId).ToList();

            var roleIds = data.Select(d => d.RoleId).Distinct().ToList();
            var merchantIds = data.Select(d => d.MerchantId).Distinct().ToList();

            var merchants = await _orgIOC._merchantEFCore.QueryAll(d => merchantIds.Contains(d.Id)).ToListAsync();
            var roles = await _orgIOC._sysRoleEFCore.QueryAll(d => roleIds.Contains(d.Id)).ToListAsync();
            foreach (var item in data)
            {
                var merchant = merchants.FirstOrDefault(d => d.Id == item.MerchantId);
                var role = roles.FirstOrDefault(d => d.Id == item.RoleId);

                item.MerchantName = merchant?.Name;
                item.MerchantCode = merchant?.MerchantCode;
                item.RoleName = role?.RoleName;
                item.RoleType = role?.RoleType;
                item.ContactPerson = merchant?.ContactPerson;
                item.ContactPhone = merchant?.ContactPhone;

            }

            return GetResult(1, data: data);
        }

        
        /// <summary>
        /// 注册商户
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> RegisteredMerchantAsync(MerchantRequestDto dto)
        {
            try
            {
                using var scope = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromMinutes(2), TransactionScopeAsyncFlowOption.Enabled);

                var user = await _orgIOC._sysUserEFCore.QueryAll(d => d.Phone == dto.ContactPhone).FirstOrDefaultAsync();
                string userId = "";
                string password = "";
                //不存在用户先创建用户
                if (user == null)
                {
                    password = Config.GenerateSecurePassword();
                    var result = await _userService.AddUserAsync(new Infrastructure.Dto.Request.User.UserRequestDto
                    {
                        Name = dto.ContactPerson,
                        Phone = dto.ContactPhone,
                        Password = password
                    });

                    if (result.code == ApiCode.fail)
                        return GetResult(message: "注册用户账户失败，请稍后重试");

                    userId = result.data.ToString();
                }

                if (string.IsNullOrEmpty(userId))
                {
                    userId = user?.Id;
                }

                string merchantId = Config.GUID();
                Merchant merchant = new Merchant()
                {
                    Id = merchantId,
                    MerchantCode = Config.GenerateCode("MER"),
                    Name = dto.Name,
                    MerchantType = (int)dto.MerchantType,//商户类型
                    Address = dto.Address,
                    DetailedAddress = dto.DetailedAddress,
                    ContactPerson = dto.ContactPerson,
                    ContactPhone = dto.ContactPhone,
                    Location = dto.Location,
                    CreationTime = DateTime.Now,
                    CreatorId = userId,
                    IsDeleted = false,
                    EnableStatus = 1,
                    AccountStatus = 0,
                    AcceptOrder = 0,
                    AcqSpId = "562294004495976"
                };

                await _orgIOC._merchantEFCore.AddAsync(merchant);
                var merchantResult = await _orgIOC._merchantEFCore.SaveChangesAsync();

                var storeResult = await AddStoreAsync(new StoreRequestDto
                {
                    Name = dto.Name + "门店",
                    StoreType = 0,
                    Address = dto.Address,
                    DetailedAddress = dto.DetailedAddress,
                    MerchantId = merchantId,
                    ContactPerson = dto.ContactPerson,
                    ContactPhone = dto.ContactPhone,
                    CreatorId = userId,
                });
                string storeId = storeResult.data.ToString();


                var role = await _orgIOC._sysRoleEFCore.QueryAll(d => d.RoleType == 2).SingleAsync();
                var sysUserRoleResult = await AddTeamMembersAsync(new UserRoleRequestDto
                {
                    RoleId = role.Id,
                    Name = dto.ContactPerson,
                    Phone = dto.ContactPhone,
                    MerchantId = merchantId,
                    CreatorId = userId,
                });

                if (merchantResult == 0 || storeResult.code == ApiCode.fail || sysUserRoleResult.code == ApiCode.fail)
                {
                    return GetResult(message: "注册商户失败，请稍后重试！");
                }

                scope.Complete();

                if (!string.IsNullOrEmpty(password))
                {
                    //发送短信通知用户
                    _smsService.SendSmsPhoneAndPassword(dto.ContactPhone, dto.ContactPhone, password);
                }

                return GetResult(1, data: new { merchant.Id, merchant.Name, merchant.ContactPerson, merchant.ContactPhone, password });

            }
            catch (Exception ex)
            {
                throw;
            }
        }

        /// <summary>
        /// 商户进件
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> MerchantEntryAsync(EpaylinksMerchantInfoRequestDto dto)
        {
            try
            {
                using var scope = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromMinutes(2), TransactionScopeAsyncFlowOption.Enabled);

                var merchant = await _orgIOC._merchantEFCore.QueryAll(d => d.Id == dto.MerId).FirstOrDefaultAsync();

                if (merchant == null)
                    return GetResult(message: "找不到该商户，请稍后重试！");

                //易票联
                var orderCode = Config.GUID();

                string sentent = "";
                var apiBaseUrl = _configuration["PaymentApi:BaseUrl"];
                string url = $"{apiBaseUrl}/api/cust/SP/Merchant/applyV2";
                merchant.Version = dto.Version;
                merchant.AcqSpId = "562294004495976";
                merchant.AcqMerId = dto.AcqMerId;
                merchant.MerId = merchant.Id;
                merchant.BackUrl = $"{_configuration["SelfUrl"]}/api/Organization/HandleMerchantAuditResultNotification";//审核结果通知地址
                merchant.MerchantName = dto.MerchantName;
                merchant.Paper = Config.SerializeToJson(dto.Paper);
                merchant.AcceptOrder = dto.AcceptOrder == "0" ? 0 : dto.AcceptOrder == "1" ? 1 : 0;
                merchant.Business = Config.SerializeToJson(dto.Business);
                merchant.BusinessBackUrl = "";
                string escapedPaper = merchant.Paper.Replace("\"", "\\\"");
                merchant.LastModificationTime = DateTime.Now;

                sentent = "{\"version\":\"" + merchant.Version + "\",\"acqSpId\":\"" + merchant.AcqSpId + "\"," +
"\"acqMerId\":\"" + merchant.AcqMerId + "\",\"merId\":\"" + merchant.MerId + "\",\"backUrl\":\"" + merchant.BackUrl + "\"," +
"\"merchantName\":\"" + merchant.MerchantName + "\",\"paper\":\"" + escapedPaper + "\"," +
"\"acceptOrder\":\"" + dto.AcceptOrder + "\",\"business\":" + merchant.Business + "," +
"\"businessBackUrl\":\"" + merchant.BusinessBackUrl + "\"}";
                //var requestObj = new
                //{
                //    version = merchant.Version,
                //    acqSpId = merchant.AcqSpId,
                //    acqMerId = merchant.AcqMerId,
                //    merId = merchant.MerId,
                //    backUrl = merchant.BackUrl,
                //    merchantName = merchant.MerchantName,
                //    paper = dto.Paper,  // 直接使用原始对象，避免双重序列化
                //    acceptOrder = dto.AcceptOrder,
                //    business = merchant.Business.StartsWith("{") ?
                //        Config.DeserializeFromJson<object>(merchant.Business) : merchant.Business,  // 处理可能已经是JSON字符串的情况
                //    businessBackUrl = merchant.BusinessBackUrl
                //};

                //sentent = Config.SerializeToJson(requestObj);
                //                sentent = "{\"version\":\"" + merchant.Version + "\",\"acqSpId\":\"" + merchant.AcqSpId + "\"," +
                //"\"acqMerId\":\"" + merchant.AcqMerId + "\",\"merId\":\"" + merchant.MerId + "\",\"backUrl\":\"" + merchant.BackUrl + "\"," +
                //"\"merchantName\":\"" + merchant.MerchantName + "\",\"paper\":" + merchant.Paper + "," +
                //"\"acceptOrder\":\"" + dto.AcceptOrder + "\",\"business\":" + merchant.Business + "," +
                //"\"businessBackUrl\":\"" + merchant.BusinessBackUrl + "\"}";

                await _orgIOC._merchantEFCore.UpdateAsync(merchant);
                var merchantResult = await _orgIOC._merchantEFCore.SaveChangesAsync();
                if (merchantResult == 0)
                    return GetResult(message: "商户进件失败，请稍后重试！");

                scope.Complete();
                //调用易票联接口
                var result = await epaylinksService.post(sentent, url);
                var res = Config.DeserializeFromJson<EpaylinksMerchantResponseDto>(result);

                return GetResult(res.RespCode == "0000" ? 1 : 0, message: res.RespMsg, data: result);
            }
            catch (Exception)
            {

                throw;
            }

        }

        /// <summary>
        /// 商户补件
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> MerchantSupplementAsync(EpaylinksMerchantInfoRequestDto dto)
        {
            try
            {
                using var scope = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromMinutes(2), TransactionScopeAsyncFlowOption.Enabled);

                var merchant = await _orgIOC._merchantEFCore.QueryAll(d => d.Id == dto.MerId).FirstOrDefaultAsync();

                if (merchant == null)
                    return GetResult(message: "找不到该商户，请稍后重试！");

                //易票联
                var orderCode = Config.GUID();

                string sentent = "";
                var apiBaseUrl = _configuration["PaymentApi:BaseUrl"];
                string url = $"{apiBaseUrl}/api/cust/SP/Merchant/updateV2";


                merchant.Version = dto.Version;
                merchant.AcqSpId = "562294004495976";
                merchant.AcqMerId = merchant.AcqMerId;
                //merchant.MerId = merchant.Id;
                merchant.BackUrl = $"{_configuration["SelfUrl"]}/api/Organization/HandleMerchantAuditResultNotification";//审核结果通知地址
                merchant.MerchantName = dto.MerchantName;
                merchant.Name = dto.MerchantName;
                merchant.Paper = Config.SerializeToJson(dto.Paper);
                string escapedPaper = merchant.Paper.Replace("\"", "\\\"");
                merchant.LastModificationTime = DateTime.Now;

                sentent = "{\"version\":\"" + merchant.Version + "\",\"acqSpId\":\"" + merchant.AcqSpId + "\"," +
    "\"acqMerId\":\"" + merchant.AcqMerId + "\",\"backUrl\":\"" + merchant.BackUrl + "\"," +
    "\"merchantName\":\"" + merchant.MerchantName + "\",\"paper\":\"" + escapedPaper + "\"}";

                await _orgIOC._merchantEFCore.UpdateAsync(merchant);
                var merchantResult = await _orgIOC._merchantEFCore.SaveChangesAsync();
                if (merchantResult == 0)
                    return GetResult(message: "商户补件失败，请稍后重试！");

                //调用易票联接口
                var result = await epaylinksService.post(sentent, url);

                scope.Complete();

                var res = Config.DeserializeFromJson<EpaylinksMerchantResponseDto>(result);

                return GetResult(res.RespCode == "0000" ? 1 : 0, message: res.RespMsg, data: result);
            }
            catch (Exception)
            {

                throw;
            }

        }

        /// <summary>
        /// 新增结算账户
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="merId"></param>
        /// <returns></returns>
        public async Task<ApiResult> AddSettlementAccountAsync(EpaylinksSettlementAccountInfo dto, string merId)
        {
            try
            {
                using var scope = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromMinutes(2), TransactionScopeAsyncFlowOption.Enabled);

                var merchant = await _orgIOC._merchantEFCore.QueryAll(d => d.Id == merId).FirstOrDefaultAsync();
                if (merchant == null)
                    return GetResult(message: "找不到该商户，请稍后重试！");

                var merchantPaper = Config.DeserializeFromJson<EpaylinksPaper>(merchant.Paper);
                merchantPaper.SettleAccountInfo = dto;
                merchant.Paper = Config.SerializeToJson(merchantPaper);

                string sentent = "";
                var apiBaseUrl = _configuration["PaymentApi:BaseUrl"];
                string url = $"{apiBaseUrl}/api/cust/SP/BankCard/add";

                // 创建匿名对象，排除所有URL结尾的字段
                var paperData = new
                {
                    SettleTarget = dto.SettleTarget,
                    SettleAccountType = dto.SettleAccountType,
                    SettleAccountNo = dto.SettleAccountNo ,
                    SettleAccount = dto.SettleAccount,
                    OpenBank = dto.OpenBank,
                    OpenSubBank = dto.OpenSubBank,
                    OpenBankCode = dto.OpenBankCode,
                    OpenBankReservePhone = dto.OpenBankReservePhone,

                    SettleCertFrontPhoto = dto.SettleCertFrontPhoto,
                    SettleCertBackPhoto = dto.SettleCertBackPhoto,
                    BankCardPhotoFront = dto.BankCardPhotoFront,
                    BankCardPhotoBack = dto.BankCardPhotoBack,
                    Postscript = dto.Postscript,
                    Summary = dto.Summary,
                    Purpose = dto.Purpose,
                    AccountIntentPhoto = dto.AccountIntentPhoto,
                    WithdrawProofPhoto = dto.WithdrawProofPhoto,
                    TransferApplyAttachment = dto.TransferApplyAttachment,
                    SettleAttachment = dto.SettleAttachment,
                    SettleLicensePhoto = dto.SettleLicensePhoto,
                    IsDefault = dto.IsDefault
                };

                string paper = Config.SerializeToJson(paperData);
                string escapedPaper = paper.Replace("\"", "\\\"");

                sentent = "{\"version\":\"" + merchant.Version + "\",\"acqSpId\":\"" + merchant.AcqSpId + "\"," +
    "\"acqMerId\":\"" + merchant.AcqMerId + "\",\"paper\":\"" + escapedPaper + "\"}";

                //调用易票联新增结算卡接口
                var result = await epaylinksService.MerchantPostRequest(sentent, url);

                await _orgIOC._merchantEFCore.UpdateAsync(merchant);
                var merchantResult = await _orgIOC._merchantEFCore.SaveChangesAsync();
                if (merchantResult == 0)
                    return GetResult(message: "修改结算账户失败，请稍后重试！");

                scope.Complete();

                var res = Config.DeserializeFromJson<EpaylinksMerchantResponseDto>(result);

                return GetResult(res.RespCode == "0000" ? 1 : 0, message: res.RespMsg, data: result);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 图片/附件上传
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> FileUploadAsync(CreateUpdateFileUploadDto dto)
        {

            string sentent = "";
            dto.AcqSpId = "562294004495976";
            var apiBaseUrl = _configuration["PaymentApi:BaseUrl"];
            string url = $"{apiBaseUrl}/api/cust/fileupload";

            sentent = Config.SerializeToJson(dto);
            //调用易票联接口
            var result = await epaylinksService.post(sentent, url);
            var res = Config.DeserializeFromJson<EpaylinksMerchantResponseDto>(result);

            return GetResult(res.RespCode == "0000" ? 1 : 0, message: res.RespMsg, data: result);
        }

        /// <summary>
        /// 商户审核结果回调通知
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<EpaylinksResponseDto> HandleMerchantAuditResultNotificationAsync(MerchantAuditResultNotificationRequest dto)
        {
            try
            {
                var merchant = await _orgIOC._merchantEFCore.QueryAll(d => d.Id == dto.merId).FirstOrDefaultAsync();
                if (merchant == null)
                    return new EpaylinksResponseDto
                    {
                        ReturnCode = "0001",
                        ReturnMsg = $"找不到该商户{dto.merId}"
                    };

                merchant.AcqMerId = dto.acqMerId;
                merchant.AuditMsg = string.IsNullOrEmpty(dto.auditMsg) ? "" : dto.auditMsg;
                merchant.AuditTime = Config.ParseTimeString(dto.auditTime);

                //if (dto.auditStatus == "1")
                //{
                //    merchant.AuditStatus = 1;//待审核
                //    merchant.AccountStatus = 0;//未开通
                //}
                if (dto.auditStatus == "2")
                {
                    merchant.AuditStatus = 2;//审核通过
                    merchant.AccountStatus = 1;//开通
                }
                if (dto.auditStatus == "3")
                {
                    merchant.AuditStatus = 3;//审核未通过
                    merchant.AccountStatus = 0;//未开通
                }
                merchant.LastModificationTime = DateTime.Now;
                await _orgIOC._merchantEFCore.UpdateAsync(merchant);
                var result = await _orgIOC._merchantEFCore.SaveChangesAsync();

                if (result >= 1)
                {
                    if (dto.auditStatus == "1")
                        return new EpaylinksResponseDto
                        {
                            ReturnCode = "0001",
                            ReturnMsg = "处理失败"
                        };

                    if (dto.auditStatus == "3")
                        return new EpaylinksResponseDto
                        {
                            ReturnCode = "0001",
                            ReturnMsg = "处理失败"
                        };

                    return new EpaylinksResponseDto
                    {
                        ReturnCode = "0000",
                        ReturnMsg = "处理成功"
                    };
                }
                else
                    return new EpaylinksResponseDto
                    {
                        ReturnCode = "0001",
                        ReturnMsg = "处理失败"
                    };
            }
            catch (Exception ex)
            {
                return new EpaylinksResponseDto
                {
                    ReturnCode = "0001",
                    ReturnMsg = "处理失败：" + ex.Message
                };
                throw;
            }
        }

        /// <summary>
        /// 查询进件商户信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> QueryMerchantAsync(QueryMerchantInfoRequestDto dto)
        {
            var merchant = await _orgIOC._merchantEFCore.QueryAll(d => d.Id == dto.MerId).FirstOrDefaultAsync();
            if (merchant == null)
                return GetResult(message: "找不到该商户，请稍后重试！");

            string sentent = "";
            var apiBaseUrl = _configuration["PaymentApi:BaseUrl"];
            string url = $"{apiBaseUrl}/api/cust/SP/Merchant/query";

            dto.AcqSpId = "562294004495976";
            string version = "2.0";
            string acqSpId = dto.AcqSpId;
            sentent = "{\"version\":\"" + version + "\",\"acqSpId\":\"" + acqSpId + "\",\"merId\":\"" + dto.MerId + "\"}";

            //调用易票联接口
            var result = await epaylinksService.post(sentent, url);
            var res = Config.DeserializeFromJson<EpaylinksMerchantResponseDto>(result);
            if (res.RespCode == "0000")
            {
                var resultData = Config.DeserializeFromJson<QueryMerchantInfoResponseDto>(result);
                var paper = Config.DeserializeFromJson<SettleAccountDto>(resultData.Paper);
                merchant.AcqMerId = resultData.AcqMerId;
                merchant.AuditMsg = string.IsNullOrEmpty(resultData.AuditMsg) ? "" : resultData.AuditMsg;
                if (resultData.AuditStatus == "1")
                {
                    merchant.AuditStatus = 1;//待审核
                    merchant.AccountStatus = 0;//未开通
                }
                if (resultData.AuditStatus == "2")
                {
                    merchant.AuditStatus = 2;//审核通过
                    merchant.AccountStatus = 1;//开通
                }
                if (resultData.AuditStatus == "3")
                {
                    merchant.AuditStatus = 3;//审核未通过
                    merchant.AccountStatus = 0;//未开通
                }
                //merchant.AuditStatus = int.TryParse(resultData.AuditStatus, out int auditStatus) ? auditStatus : 0; // 失败时使用默认值0 ;
                //merchant.AccountStatus = int.TryParse(resultData.AccountStatus, out int accountStatus) ? accountStatus : 0;
                merchant.LastModificationTime = DateTime.Now;

                await _orgIOC._merchantEFCore.UpdateAsync(merchant);
                var merchantResult = await _orgIOC._merchantEFCore.SaveChangesAsync();
            }

            return GetResult(res.RespCode == "0000" ? 1 : 0, message: res.RespMsg, data: result);
        }

        /// <summary>
        /// 获取用户商户列表
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult> GetUserMerchantListAsync()
        {
            var userId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
            var data = await _orgIOC._merchantEFCore.QueryAll(d => (string.IsNullOrEmpty(userId) || d.CreatorId.Contains(userId))).Select(d => new MerchantResponseDto
            {
                Id = d.Id,
                MerchantCode = d.MerchantCode,
                Name = d.Name,
                MerchantType = d.MerchantType,
                Address = d.Address,
                DetailedAddress = d.DetailedAddress,
                ContactPerson = d.ContactPerson,
                ContactPhone = d.ContactPhone,
                CreationTime = d.CreationTime,
                CreatorId = d.CreatorId,
                LastModificationTime = d.LastModificationTime,
                LastModifierId = d.LastModifierId,
                IsDeleted = d.IsDeleted,
                DeleterId = d.DeleterId,
                DeletionTime = d.DeletionTime,
                EnableStatus = d.EnableStatus,
                SettlementCycle = d.SettlementCycle,
                AccountStatus = d.AccountStatus,
                AuditStatus = d.AuditStatus,
                Location = d.Location,
                Paper = Config.DeserializeFromJson<EpaylinksPaper>(d.Paper)
            }).ToListAsync();

            data.ForEach(d =>
            {
                d.BankUserName = d.Paper?.SettleAccountInfo?.SettleAccount;
                d.BankCardNo = Config.MaskBankCardNo(d.Paper?.SettleAccountInfo?.SettleAccountNo);
                d.BankName = d.Paper?.SettleAccountInfo?.OpenBank;
                d.Paper = null;
            });

            return GetResult(1, data: data);
        }

        /// <summary>
        /// 获取商户列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetMerchantListAsync(MerchantRequestDto dto)
        {
            var data = await _orgIOC._merchantEFCore.QueryAll(out int total, dto.Page, dto.Limit,
                d => (string.IsNullOrEmpty(dto.Key) || d.Name.Contains(dto.Key)),
                d => d.CreationTime, false)
                .Select(d => new MerchantResponseDto
                {
                    Id = d.Id,
                    MerchantCode = d.MerchantCode,
                    Name = d.Name,
                    MerchantType = d.MerchantType,
                    Address = d.Address,
                    DetailedAddress = d.DetailedAddress,
                    ContactPerson = d.ContactPerson,
                    ContactPhone = d.ContactPhone,
                    CreationTime = d.CreationTime,
                    CreatorId = d.CreatorId,
                    LastModificationTime = d.LastModificationTime,
                    LastModifierId = d.LastModifierId,
                    IsDeleted = d.IsDeleted,
                    DeleterId = d.DeleterId,
                    DeletionTime = d.DeletionTime,
                    EnableStatus = d.EnableStatus,
                    SettlementCycle = d.SettlementCycle,
                    AccountStatus = d.AccountStatus,
                    AuditStatus = d.AuditStatus,
                    Location = d.Location
                })
                .ToListAsync();

            return GetResult(1, data: new
            {
                data,
                total
            });
        }

        /// <summary>
        /// 获取单个商户详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetMerchantDetailAsync(string Id)
        {
            var data = await _orgIOC._merchantEFCore.QueryAll(d => d.Id == Id)
                .Select(d => new MerchantResponseDto
                {
                    Id = d.Id,
                    MerchantCode = d.MerchantCode,
                    Name = d.Name,
                    MerchantType = d.MerchantType,
                    Address = d.Address,
                    DetailedAddress = d.DetailedAddress,
                    ContactPerson = d.ContactPerson,
                    ContactPhone = d.ContactPhone,
                    CreationTime = d.CreationTime,
                    CreatorId = d.CreatorId,
                    LastModificationTime = d.LastModificationTime,
                    LastModifierId = d.LastModifierId,
                    IsDeleted = d.IsDeleted,
                    DeleterId = d.DeleterId,
                    DeletionTime = d.DeletionTime,
                    EnableStatus = d.EnableStatus,
                    SettlementCycle = d.SettlementCycle,
                    AccountStatus = d.AccountStatus,
                    AuditStatus = d.AuditStatus,
                    Location = d.Location
                })
                .FirstOrDefaultAsync();

            return GetResult(1, data: data);
        }

        /// <summary>
        /// 获取单个商户进件信息详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetMerchantEntryDetailAsync(string Id)
        {
            var data = await _orgIOC._merchantEFCore.QueryAll(d => d.Id == Id)
                .Select(d => new MerchantResponseDto
                {
                    Id = d.Id,
                    MerchantName = d.MerchantName,
                    AcqSpId = d.AcqSpId,
                    AcqMerId = d.AcqMerId,
                    MerId = d.MerId,
                    Paper = Config.DeserializeFromJson<EpaylinksPaper>(d.Paper),
                    AcceptOrder = d.AcceptOrder,
                    AccountStatus = d.AccountStatus,
                    AuditStatus = d.AuditStatus,
                    AuditMsg = d.AuditMsg,
                    AuditTime = d.AuditTime,
                    Business = Config.DeserializeFromJson<List<EpaylinksBusinessInfo>>(d.Business),
                })
                .FirstOrDefaultAsync();

            //data.Paper.SettleAccountInfo.SettleAccountNo = Config.MaskBankCardNo(data.Paper.SettleAccountInfo.SettleAccountNo);
            //data.Paper.OpenAccountInfo.LicenceAccountNo = Config.MaskBankCardNo(data.Paper.OpenAccountInfo.LicenceAccountNo);
            //data.Paper.LawyerInfo.LawyerCertNo = Config.MaskIdCardNo(data.Paper.LawyerInfo.LawyerCertNo);

            return GetResult(1, data: data);

        }

        /// <summary>
        /// 编辑商户信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> UpdateMerchantAsync(MerchantRequestDto dto)
        {
            try
            {
                using var scope = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromMinutes(2), TransactionScopeAsyncFlowOption.Enabled);

                var merchant = await _orgIOC._merchantEFCore.QueryAll(d => d.Id == dto.Id).FirstOrDefaultAsync();
                if (merchant == null)
                    return GetResult(message: "找不到该商户，请稍后重试！");

                merchant.Name = dto.Name;
                merchant.MerchantType = (int)dto.MerchantType;
                merchant.Address = dto.Address;
                merchant.DetailedAddress = dto.DetailedAddress;
                merchant.ContactPerson = dto.ContactPerson;
                merchant.ContactPhone = dto.ContactPhone;
                merchant.Location = dto.Location;
                merchant.LastModificationTime = DateTime.Now;
                merchant.LastModifierId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
                //merchant.EnableStatus = (int)dto.EnableStatus;

                await _orgIOC._merchantEFCore.UpdateAsync(merchant);
                var result = await _orgIOC._merchantEFCore.SaveChangesAsync();

                if (result == 0)
                    return GetResult(message: "编辑商户信息失败，请稍后重试！");

                scope.Complete();
                return GetResult(result);

            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 删除商户
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> DeleteMerchantAsync(MerchantRequestDto dto)
        {
            return GetResult(0);
        }

        /// <summary>
        /// 新增门店
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> AddStoreAsync(StoreRequestDto dto)
        {
            try
            {
                using var scope = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromMinutes(2), TransactionScopeAsyncFlowOption.Enabled);

                Store store = new Store()
                {
                    Id = Config.GUID(),
                    StoreCode = Config.GenerateCode("STO"),
                    Name = dto.Name,
                    Address = dto.Address,
                    DetailedAddress = dto.DetailedAddress,
                    StoreType = (int)dto.StoreType,
                    MerchantId = dto.MerchantId,
                    ContactPerson = dto.ContactPerson,
                    ContactPhone = dto.ContactPhone,
                    SettlementCycle = dto.SettlementCycle,
                    CreationTime = DateTime.Now,
                    CreatorId = dto.CreatorId ?? _httpContextAccessor.HttpContext?.GetCurrentUserId(),
                    IsDeleted = false,
                    EnableStatus = 1,
                    ExtraProperties = dto.ExtraProperties,
                    ThumbnailUrl = dto.ThumbnailUrl,
                    Location = dto.Location,
                };

                await _orgIOC._storeEFCore.AddAsync(store);
                var result = await _orgIOC._storeEFCore.SaveChangesAsync();

                var paymentCodeResult = await _paymentCodeService.AddPaymentCodeAsync(new Infrastructure.Dto.Request.Payment.PaymentCodeRequestDto
                {
                    MerchantId = dto.MerchantId,
                    StoreId = store.Id,
                    CodeName = dto.Name + "的收款码",
                    CreatorId = dto.CreatorId ?? _httpContextAccessor.HttpContext?.GetCurrentUserId(),
                });

                scope.Complete();
                return GetResult(result, data: store.Id);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 获取门店列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetStoreListAsync(StoreRequestDto dto)
        {
            var permission = await _userService.GetCurUserRolePermissionAsync();
            List<string> storeIds = new List<string>();
            if (permission != null)
            {
                if (permission.RoleType == 4 || permission.RoleType == 5)//店长
                {
                    storeIds = permission.StoreIds;
                    if (storeIds.Count() < 1)
                        return GetResult(1,"无关联数据");
                }

                if (storeIds.Count == 0 && !string.IsNullOrEmpty(dto.Id))
                    storeIds.Add(dto.Id);
            }

            var data = await _orgIOC._storeEFCore.QueryAll(out int total, dto.Page, dto.Limit,
                d => (string.IsNullOrEmpty(dto.Key) || d.Name.Contains(dto.Key))
                && (string.IsNullOrEmpty(dto.MerchantId) || d.MerchantId.Contains(dto.MerchantId))
                && (!storeIds.Any() || storeIds.Contains(d.Id)),
                d => d.CreationTime, false).Select(d => new StoreRequestDto
                {
                    Id = d.Id,
                    Name = d.Name,
                    StoreCode = d.StoreCode,
                    Address = d.Address,
                    DetailedAddress = d.DetailedAddress,
                    CreationTime = d.CreationTime,
                    ContactPerson = d.ContactPerson,
                    ContactPhone = d.ContactPhone,
                    EnableStatus = d.EnableStatus,
                    StoreType = d.StoreType,
                    MerchantId = d.MerchantId,
                    CreatorId = d.CreatorId,
                    ExtraProperties = d.ExtraProperties,
                    ThumbnailUrl = d.ThumbnailUrl,
                    Location = d.Location,
                }).ToListAsync();

            var roleId = await _orgIOC._sysRoleEFCore.QueryAll(d => d.RoleType == 5).Select(d => d.Id).FirstOrDefaultAsync();

            foreach (var store in data)
            {
                //查询关联团队成员
                var userRole = await _orgIOC._sysUserRoleEFCore.QueryAll(
                    d => d.MerchantId == store.MerchantId
                    && d.StoreId == store.Id
                    && d.RoleId == roleId).ToListAsync();

                userRole.ForEach(d =>
                {
                    store.BindUserId.Add(d.Id);
                    store.BindUserName.Add(d.Name);
                });
            }

            return GetResult(1, data: new
            {
                data,
                total
            });
        }

        /// <summary>
        /// 获取单个门店详情
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetStoreDetailAsync(StoreRequestDto dto)
        {
            var data = await _orgIOC._storeEFCore.QueryAll(d => d.Id == dto.Id).Select(d => new StoreRequestDto
            {
                Id = d.Id,
                MerchantId = d.MerchantId,
                Name = d.Name,
                StoreCode = d.StoreCode,
                Address = d.Address,
                DetailedAddress = d.DetailedAddress,
                CreationTime = d.CreationTime,
                ContactPerson = d.ContactPerson,
                ContactPhone = d.ContactPhone,
                EnableStatus = d.EnableStatus,
                StoreType = d.StoreType,
                SettlementCycle = d.SettlementCycle,
                ExtraProperties = d.ExtraProperties,
                ThumbnailUrl = d.ThumbnailUrl,
                Location = d.Location,
            }).SingleOrDefaultAsync();

            var roleId = await _orgIOC._sysRoleEFCore.QueryAll(d => d.RoleType == 5).Select(d => d.Id).FirstOrDefaultAsync();

            var userRole = await _orgIOC._sysUserRoleEFCore.QueryAll(
                d => d.MerchantId == data.MerchantId
                && d.StoreId == data.Id
                && d.RoleId == roleId).ToListAsync();

            userRole.ForEach(d =>
            {
                data.BindUserId.Add(d.Id);
                data.BindUserName.Add(d.Name);
            });

            return GetResult(1, data: data);
        }

        /// <summary>
        /// 在门店详情里批量设置关联成员
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> SetStoreMembersAsync(BindMembersRequestDto dto)
        {
            try
            {
                if (string.IsNullOrEmpty(dto.StoreId))
                    return GetResult(message: "参数错误：门店ID不能为空");

                var txOptions = new System.Transactions.TransactionOptions
                {
                    IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted, //防脏读
                    Timeout = TimeSpan.FromMinutes(2)
                };
                using var scope = new TransactionScope(TransactionScopeOption.Required, txOptions, TransactionScopeAsyncFlowOption.Enabled);

                var store = await _orgIOC._storeEFCore.QueryAll(d => d.Id == dto.StoreId).FirstOrDefaultAsync();
                if (store == null)
                    return GetResult(message: "找不到门店，请稍后重试！");

                // Merchant 校验（若入参传了 MerchantId 则做一致性校验）
                if (!string.IsNullOrEmpty(dto.MerchantId) && !string.Equals(store.MerchantId, dto.MerchantId, StringComparison.OrdinalIgnoreCase))
                    return GetResult(message: "参数错误：商户不匹配");

                var targetIds = (dto.UserRoleIds ?? new List<string>()).Distinct().ToList();

                // 当前已绑定到该门店的成员
                var currentIds = await _orgIOC._sysUserRoleEFCore.QueryAll(d =>
                        d.MerchantId == store.MerchantId && d.StoreId == store.Id)
                    .Select(d => d.Id)
                    .ToListAsync();

                var toUnbindIds = currentIds.Except(targetIds).ToList();
                var toBindIds = targetIds.Except(currentIds).ToList();

                int affected = 0;

                // 解绑：从该门店移除（并清理 CodeId，避免残留该门店下收款码绑定）
                if (toUnbindIds.Count > 0)
                {
                    var unbindList = await _orgIOC._sysUserRoleEFCore.QueryAll(d =>
                            toUnbindIds.Contains(d.Id) && d.MerchantId == store.MerchantId && d.StoreId == store.Id)
                        .ToListAsync();

                    foreach (var ur in unbindList)
                    {
                        ur.StoreId = null;
                        ur.CodeId = null;
                        ur.LastModificationTime = DateTime.Now;
                        ur.LastModifierId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
                    }

                    if (unbindList.Count > 0)
                    {
                        await _orgIOC._sysUserRoleEFCore.UpdateRangeAsync(unbindList);
                        affected += await _orgIOC._sysUserRoleEFCore.SaveChangesAsync();
                    }
                }

                // 绑定：为该门店新增成员记录（而不是把原有记录的 StoreId 改到本店），以支持“一个成员多个门店”
                if (toBindIds.Count > 0)
                {
                    // 基准记录：用于取 UserId/RoleId/MerchantId/Name（不修改这些记录）
                    var baseList = await _orgIOC._sysUserRoleEFCore.QueryAll(d =>
                            toBindIds.Contains(d.Id) && d.MerchantId == store.MerchantId)
                        .ToListAsync();

                    if (baseList.Count > 0)
                    {
                        var baseUserIds = baseList.Select(x => x.UserId).Distinct().ToList();
                        var baseRoleIds = baseList.Select(x => x.RoleId).Distinct().ToList();

                        // 已存在于“当前门店”的记录，做幂等判断（UserId+RoleId 维度）
                        var existAtThisStore = await _orgIOC._sysUserRoleEFCore.QueryAll(d =>
                                d.MerchantId == store.MerchantId
                                && d.StoreId == store.Id
                                && baseUserIds.Contains(d.UserId)
                                && baseRoleIds.Contains(d.RoleId))
                            .Select(d => new { d.UserId, d.RoleId })
                            .ToListAsync();

                        var existKeys = new HashSet<string>(existAtThisStore.Select(e => $"{e.UserId}:{e.RoleId}"));

                        var newList = new List<SysUserRole>();
                        var creatorId = _httpContextAccessor.HttpContext?.GetCurrentUserId();

                        foreach (var br in baseList)
                        {
                            var key = $"{br.UserId}:{br.RoleId}";
                            if (existKeys.Contains(key))
                                continue; // 幂等：已有同人同角色在该门店，跳过

                            newList.Add(new SysUserRole
                            {
                                Id = Config.GUID(),
                                UserId = br.UserId,
                                RoleId = br.RoleId,
                                MerchantId = store.MerchantId,
                                StoreId = store.Id, // 绑定该门店
                                CodeId = null,      // 门店成员绑定不强制指定码；如需同步码绑定，由“码详情批量设置成员”处理
                                Name = br.Name,
                                CreationTime = DateTime.Now,
                                CreatorId = creatorId,
                                IsDeleted = false,
                                EnableStatus = 1,
                            });
                        }

                        if (newList.Count > 0)
                        {
                            await _orgIOC._sysUserRoleEFCore.AddRangeAsync(newList);
                            affected += await _orgIOC._sysUserRoleEFCore.SaveChangesAsync();
                        }
                    }
                }

                if (affected == 0)
                    return GetResult(message: "设置关联成员失败，请稍后重试！");

                scope.Complete();
                return GetResult(affected);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 编辑门店信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> UpdateStoreAsync(StoreRequestDto dto)
        {
            try
            {
                using var scope = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromMinutes(2), TransactionScopeAsyncFlowOption.Enabled);
                var store = await _orgIOC._storeEFCore.QueryAll(d => d.Id == dto.Id).FirstOrDefaultAsync();
                if (store == null)
                {
                    return GetResult(message: "参数错误");
                }
                store.Name = dto.Name;
                store.Address = dto.Address;
                store.DetailedAddress = dto.DetailedAddress;
                store.StoreType = (int)dto.StoreType;
                store.ContactPerson = dto.ContactPerson;
                store.ContactPhone = dto.ContactPhone;
                store.SettlementCycle = dto.SettlementCycle;
                store.LastModificationTime = DateTime.Now;
                store.LastModifierId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
                store.ThumbnailUrl = dto.ThumbnailUrl;
                store.Location = dto.Location;
                //store.EnableStatus = (int)dto.EnableStatus;

                await _orgIOC._storeEFCore.UpdateAsync(store);
                var result = await _orgIOC._storeEFCore.SaveChangesAsync();

                if (result == 0)
                    return GetResult(message: "编辑门店信息失败，请稍后重试！");

                scope.Complete();
                return GetResult(result);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 删除门店
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> DeleteStoreAsync(StoreRequestDto dto)
        {
            return GetResult(0);
        }

        /// <summary>
        /// 更新登录用户的角色选择（用户切换商户角色）
        /// </summary>
        /// <param name="userRoleId"></param>
        /// <returns></returns>
        public async Task<ApiResult> UpdateLoginUserRoleAsync(string userRoleId)
        {
            try
            {
                await _unitOfWork.BeginTransactionAsync(System.Data.IsolationLevel.ReadCommitted);

                var userId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
                var userRole = await _orgIOC._sysUserRoleEFCore.QueryAll(d => d.Id == userRoleId && d.UserId == userId).FirstOrDefaultAsync();
                if (userRole == null)
                    return GetResult(message: "找不到该用户角色，请稍后重试！");
                var user = await _orgIOC._sysUserEFCore.QueryAll(d => d.Id == userId).FirstOrDefaultAsync();
                if (user == null)
                    return GetResult(message: "找不到该用户，请稍后重试！");

                if (user.CurrentUserRoleId != userRole.Id)
                {
                    user.CurrentUserRoleId = userRole.Id;

                    await _orgIOC._sysUserEFCore.UpdateAsync(user);
                    var result = await _orgIOC._sysUserEFCore.SaveChangesAsync();
                    if (result == 0)
                        return GetResult(message: "切换商户角色失败，请稍后重试！");
                }
                await _unitOfWork.CommitAsync();

                return GetResult(1);
            }
            catch (Exception)
            {
                await _unitOfWork.RollbackAsync();
                throw;
            }
        }

        /// <summary>
        /// 检查当前手机号的用户是否在该商户下存在角色
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> CheckTeamMembersAsync(UserRoleRequestDto dto)
        {
            var user = await _orgIOC._sysUserEFCore.QueryAll(d => d.Phone == dto.Phone).FirstOrDefaultAsync();
            if (user == null)
                return GetResult(1, message: "当前校验手机号不是系统用户");
            var userRole = await _orgIOC._sysUserRoleEFCore.QueryAll(d => d.UserId == user.Id && dto.MerchantId == d.MerchantId).FirstOrDefaultAsync();
            if (userRole == null)
                return GetResult(1, message: "当前校验手机号不在该商户下面存在角色");

            return GetResult(0, message: "当前手机号已在商户下存在角色，请勿重复添加");
        }

        /// <summary>
        /// 检查手机号用户是否存在
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public async Task<bool> CheckUserAsync(string phone)
        {
            var user = await _orgIOC._sysUserEFCore.QueryAll(d => d.Phone == phone).FirstOrDefaultAsync();
            if (user == null)
                return false;

            return true;
        }

        /// <summary>
        /// 新增团队成员
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> AddTeamMembersAsync(UserRoleRequestDto dto)
        {
            try
            {
                using var scope = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromMinutes(2), TransactionScopeAsyncFlowOption.Enabled);

                var user = await _orgIOC._sysUserEFCore.QueryAll(d => d.Phone == dto.Phone).FirstOrDefaultAsync();
                string userId = "";
                //不存在用户先创建用户
                if (user == null)
                {
                    var result = await _userService.AddUserAsync(new Infrastructure.Dto.Request.User.UserRequestDto
                    {
                        Phone = dto.Phone,
                        Name = dto.Name
                    });
                    userId = result.data.ToString();
                }
                else
                {
                    userId = user.Id;
                }
                 
                var role = await _orgIOC._sysRoleEFCore.QueryAll(d => d.Id == dto.RoleId).FirstOrDefaultAsync();
                if (role == null)
                    return GetResult(message: "找不到该角色，请稍后重试！");

                List<SysUserRole> userRoles = new List<SysUserRole>();
                if (role.RoleType == 4 || role.RoleType == 5)
                {
                    if (dto.StoreIds.Count == 0)
                        dto.StoreIds.Add("");
                    foreach (var storeId in dto.StoreIds)
                    {
                        SysUserRole userRole = new SysUserRole()
                        {
                            Id = Config.GUID(),
                            UserId = userId,
                            RoleId = dto.RoleId,
                            MerchantId = dto.MerchantId,
                            StoreId = storeId,
                            CodeId = "",
                            Name = dto.Name,
                            CreationTime = DateTime.Now,
                            CreatorId = dto.CreatorId,
                            IsDeleted = false,
                            EnableStatus = 0,
                        };
                        userRoles.Add(userRole);
                    }
                }
                if (role.RoleType == 6)
                {
                    if (dto.CodeIds.Count == 0)
                        dto.CodeIds.Add("");
                    foreach (var codeId in dto.CodeIds)
                    {
                        SysUserRole userRole = new SysUserRole()
                        {
                            Id = Config.GUID(),
                            UserId = userId,
                            RoleId = dto.RoleId,
                            MerchantId = dto.MerchantId,
                            StoreId = "",
                            CodeId = codeId,
                            Name = dto.Name,
                            CreationTime = DateTime.Now,
                            CreatorId = dto.CreatorId,
                            IsDeleted = false,
                            EnableStatus = 0,
                        };
                        userRoles.Add(userRole);
                    }
                }
               
                await _orgIOC._sysUserRoleEFCore.AddRangeAsync(userRoles);
                var sysUserRoleResult = await _orgIOC._sysUserRoleEFCore.SaveChangesAsync();

                if (sysUserRoleResult == 0)
                {
                    return GetResult(message: "新增团队成员失败，请稍后重试！");
                }

                scope.Complete();
                return GetResult(1, data: userRoles[0].Id);
            }

            catch (Exception)
            {
                throw;
            }

        }

        /// <summary>
        /// 团队成员确认加入
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> TramMembersConfirmAsync(UserRoleRequestDto dto)
        {
            try
            {
                await _unitOfWork.BeginTransactionAsync(System.Data.IsolationLevel.ReadCommitted);

                var user = await _orgIOC._sysUserEFCore.QueryAll(d => d.Phone == dto.Phone).FirstOrDefaultAsync();
                if (user == null)
                    return GetResult(message: "当前手机号不是系统用户");
                var isCode = await _smsService.VerifyCodeAsync(dto.Phone, dto.Code);

                if (!isCode)
                    return GetResult(message: "验证码错误，请重新输入");

                string password = "";
                if (string.IsNullOrEmpty(user.Password))
                {
                    password = Config.GenerateSecurePassword();
                    user.Password = EncryptionUtility.HashPassword(password);
                }

                //var userRole = await _orgIOC._sysUserRoleEFCore.QueryAll(d => d.UserId == user.Id && dto.MerchantId == d.MerchantId && d.RoleId == dto.RoleId).FirstOrDefaultAsync();
                var userRole = await _orgIOC._sysUserRoleEFCore.QueryAll(d => d.Id == dto.Id).FirstOrDefaultAsync();
                if (userRole == null)
                    return GetResult(message: "当前手机号不在该商户下面存在角色");
                userRole.Name = dto.Name;
                userRole.EnableStatus = 1;
                userRole.LastModificationTime = DateTime.Now;
                userRole.LastModifierId = user.Id;

                await _orgIOC._sysUserRoleEFCore.UpdateAsync(userRole);
                var result = await _orgIOC._sysUserRoleEFCore.SaveChangesAsync();
                if (result == 0)
                    return GetResult(message: "确认加入失败，请稍后重试！");

                await _unitOfWork.CommitAsync();

                if (!string.IsNullOrEmpty(password))
                    _smsService.SendSmsPhoneAndPassword(dto.Phone, dto.Phone, password);

                return GetResult(result);

            }
            catch (Exception)
            {
                await _unitOfWork.RollbackAsync();
                throw;
            }
        }

        /// <summary>
        /// 获取团队成员列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetTeamMembersListAsync(UserRoleRequestDto dto)
        {
            var query = _orgIOC._sysUserRoleEFCore.QueryAll(out int total, dto.Page, dto.Limit,
        d => (string.IsNullOrEmpty(dto.Key) || d.Name.Contains(dto.Key))
        && (string.IsNullOrEmpty(dto.MerchantId) || d.MerchantId.Contains(dto.MerchantId))
        && (string.IsNullOrEmpty(dto.StoreId) || d.StoreId.Contains(dto.StoreId)),
        d => d.CreationTime, false);

            var list = await query.ToListAsync();

            var data = list
                .DistinctBy(d => d.UserId) // 去重
                .Select(d => new UserRoleRequestDto
                {
                    Id = d.Id,
                    UserId = d.UserId,
                    RoleId = d.RoleId,
                    MerchantId = d.MerchantId,
                    StoreId = d.StoreId,
                    CodeId = d.CodeId,
                    Name = d.Name,
                    CreationTime = d.CreationTime,
                    CreatorId = d.CreatorId,
                    IsDeleted = d.IsDeleted,
                    EnableStatus = d.EnableStatus,
                }).ToList();


            var role = await _orgIOC._sysRoleEFCore.QueryAll(d => data.Select(e => e.RoleId).Contains(d.Id)).ToListAsync();
            var user = await _orgIOC._sysUserEFCore.QueryAll(d => data.Select(e => e.UserId).Contains(d.Id)).ToListAsync();

            foreach (var userRole in data)
            {
                userRole.RoleName = role.Where(d => d.Id == userRole.RoleId).Select(d => d.RoleName).FirstOrDefault();
                userRole.Phone = user.Where(d => d.Id == userRole.UserId).Select(d => d.Phone).FirstOrDefault();
                userRole.RoleType = role.Where(d => d.Id == userRole.RoleId).Select(d => d.RoleType).FirstOrDefault();
            }

            if (dto.RoleType != -1)
                data = data.Where(d => d.RoleType == dto.RoleType).ToList();

            total = data.Count();
            return GetResult(1, data: new
            {
                total,
                data
            });
        }

        /// <summary>
        /// 获取单个团队成员详细信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetTeamMembersAsync(UserRoleRequestDto dto)
        {
            var data = await _orgIOC._sysUserRoleEFCore.QueryAll(d => d.Id == dto.Id).Select(d => new UserRoleRequestDto
            {
                Id = d.Id,
                UserId = d.UserId,
                RoleId = d.RoleId,
                MerchantId = d.MerchantId,
                StoreId = d.StoreId,
                CodeId = d.CodeId,
                Name = d.Name,
                CreationTime = d.CreationTime,
                CreatorId = d.CreatorId,
                IsDeleted = d.IsDeleted,
                EnableStatus = d.EnableStatus,
            }).FirstOrDefaultAsync();

            if (data == null)
                return GetResult(message: "未找到该团队成员信息");

            var role = await _orgIOC._sysRoleEFCore.QueryAll(d => d.Id == data.RoleId).FirstOrDefaultAsync();
            data.RoleName = role.RoleName;
            data.RoleType = role.RoleType;
            data.Phone = await _orgIOC._sysUserEFCore.QueryAll(d => d.Id == data.UserId).Select(d => d.Phone).FirstOrDefaultAsync();

            // 聚合同一成员（同 MerchantId+UserId+RoleId）的所有门店/收款码
            var allRows = await _orgIOC._sysUserRoleEFCore.QueryAll(d =>
                    d.MerchantId == data.MerchantId
                    && d.UserId == data.UserId
                    && d.RoleId == data.RoleId)
                .ToListAsync();

            var storeIds = allRows.Where(x => !string.IsNullOrEmpty(x.StoreId)).Select(x => x.StoreId).Distinct().ToList();
            var codeIds = allRows.Where(x => !string.IsNullOrEmpty(x.CodeId)).Select(x => x.CodeId).Distinct().ToList();

            data.StoreIds = storeIds ?? new List<string>();
            data.CodeIds = codeIds ?? new List<string>();

            if (storeIds.Count > 0)
            {
                var stores = await _orgIOC._storeEFCore.QueryAll(s => storeIds.Contains(s.Id))
                    .Select(s => new { s.Id, s.Name })
                    .ToListAsync();
                // 为兼容现有前端，名称用逗号拼接
                data.StoreName = string.Join(",", stores.Select(s => s.Name));
            }

            if (codeIds.Count > 0)
            {
                var codes = await _orgIOC._paymentCodeEFCore.QueryAll(c => codeIds.Contains(c.Id))
                    .Select(c => new { c.Id, c.CodeName })
                    .ToListAsync();
                // 为兼容现有前端，名称用逗号拼接
                data.CodeName = string.Join(",", codes.Select(c => c.CodeName));
            }

            return GetResult(1, data: data);
        }
        /// <summary>
        /// 编辑团队成员信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> UpdateTeamMembersAsync(UserRoleRequestDto dto)
        {
            try
            {
                var txOptions = new System.Transactions.TransactionOptions
                {
                    IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted,
                    Timeout = TimeSpan.FromMinutes(2)
                };
                using var scope = new TransactionScope(TransactionScopeOption.Required, txOptions, TransactionScopeAsyncFlowOption.Enabled);

                var userRole = await _orgIOC._sysUserRoleEFCore.QueryAll(d => d.Id == dto.Id).FirstOrDefaultAsync();
                if (userRole == null)
                    return GetResult(message: "未找到该团队成员信息，请稍后重试！");



                // 记录旧角色信息，便于切换角色后做清理
                var oldRoleId = userRole.RoleId;
                var oldRole = await _orgIOC._sysRoleEFCore.QueryAll(d => d.Id == oldRoleId).FirstOrDefaultAsync();
                var oldRoleType = oldRole?.RoleType ?? -1;

                // 基础信息更新（仅角色；昵称统一在“全量同步昵称”）
                var roleChanged = !string.IsNullOrEmpty(dto.RoleId) && dto.RoleId != userRole.RoleId;
                if (roleChanged)
                    userRole.RoleId = dto.RoleId!;

                userRole.LastModificationTime = DateTime.Now;
                userRole.LastModifierId = _httpContextAccessor.HttpContext?.GetCurrentUserId();

                await _orgIOC._sysUserRoleEFCore.UpdateAsync(userRole);
                var baseAffected = await _orgIOC._sysUserRoleEFCore.SaveChangesAsync();

                // 去掉早退逻辑，避免仅发生绑定变更时被误判失败
                // if (baseAffected == 0) return GetResult(message: "编辑团队成员失败，请稍后重试！");

                // 新角色类型（区分店长/监事/收银员）
                var role = await _orgIOC._sysRoleEFCore.QueryAll(d => d.Id == userRole.RoleId).FirstOrDefaultAsync();
                var roleType = role?.RoleType ?? -1;

                int affected = baseAffected;

                // 如果发生角色变更，需要对“旧角色类型”的绑定做清理
                if (roleChanged)
                {
                    // 旧：店长/监事(4/5) -> 新：非(4/5)，清空旧角色所有门店/收款码绑定
                    if ((oldRoleType == 4 || oldRoleType == 5) && !(roleType == 4 || roleType == 5))
                    {
                        var oldRows = await _orgIOC._sysUserRoleEFCore.QueryAll(d =>
                                d.MerchantId == userRole.MerchantId
                                && d.UserId == userRole.UserId
                                && d.RoleId == oldRoleId)
                            .ToListAsync();
                        foreach (var ur in oldRows)
                        {
                            ur.StoreId = null;
                            ur.CodeId = null;
                            ur.LastModificationTime = DateTime.Now;
                            ur.LastModifierId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
                        }
                        if (oldRows.Count > 0)
                        {
                            await _orgIOC._sysUserRoleEFCore.UpdateRangeAsync(oldRows);
                            affected += await _orgIOC._sysUserRoleEFCore.SaveChangesAsync();
                        }
                    }

                    // 旧：收银员(6) -> 新：非6，清空旧角色所有收款码绑定（保留门店）
                    if (oldRoleType == 6 && roleType != 6)
                    {
                        var oldRows = await _orgIOC._sysUserRoleEFCore.QueryAll(d =>
                                d.MerchantId == userRole.MerchantId
                                && d.UserId == userRole.UserId
                                && d.RoleId == oldRoleId
                                && d.CodeId != null)
                            .ToListAsync();
                        foreach (var ur in oldRows)
                        {
                            ur.CodeId = null;
                            ur.LastModificationTime = DateTime.Now;
                            ur.LastModifierId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
                        }
                        if (oldRows.Count > 0)
                        {
                            await _orgIOC._sysUserRoleEFCore.UpdateRangeAsync(oldRows);
                            affected += await _orgIOC._sysUserRoleEFCore.SaveChangesAsync();
                        }
                    }
                }

                // 店长/监事：支持多店绑定（新增支持 roleType=4）
                if (roleType == 4 || roleType == 5)
                {
                    // 目标门店集合：优先使用列表，未传列表则回退单值
                    var targetStoreIds = (dto.StoreIds ?? new List<string>()).Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList();
                    if (targetStoreIds.Count == 0 && !string.IsNullOrWhiteSpace(dto.StoreId))
                        targetStoreIds = new List<string> { dto.StoreId };

                    // 当前该成员在此商户下、同角色的“门店绑定”
                    var currentStoreRows = await _orgIOC._sysUserRoleEFCore.QueryAll(d =>
                            d.MerchantId == userRole.MerchantId
                            && d.UserId == userRole.UserId
                            && d.RoleId == userRole.RoleId
                            && d.StoreId != null)
                        .ToListAsync();
                    var currentStoreIds = currentStoreRows.Select(d => d.StoreId!).Distinct().ToList();

                    var toUnbindStores = currentStoreIds.Except(targetStoreIds).ToList();
                    var toBindStores = targetStoreIds.Except(currentStoreIds).ToList();

                    // 解绑：清空 StoreId 和 CodeId（不再分散设置 Name）
                    if (toUnbindStores.Count > 0)
                    {
                        var unbindList = currentStoreRows.Where(d => toUnbindStores.Contains(d.StoreId!)).ToList();
                        foreach (var ur in unbindList)
                        {
                            ur.StoreId = null;
                            ur.CodeId = null;
                            ur.LastModificationTime = DateTime.Now;
                            ur.LastModifierId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
                        }
                        if (unbindList.Count > 0)
                        {
                            await _orgIOC._sysUserRoleEFCore.UpdateRangeAsync(unbindList);
                            affected += await _orgIOC._sysUserRoleEFCore.SaveChangesAsync();
                        }
                    }

                    // 绑定：优先复用空闲记录（StoreId==null && CodeId==null），不够则新增
                    if (toBindStores.Count > 0)
                    {
                        var freeRows = await _orgIOC._sysUserRoleEFCore.QueryAll(d =>
                                d.MerchantId == userRole.MerchantId
                                && d.UserId == userRole.UserId
                                && d.RoleId == userRole.RoleId
                                && d.StoreId == null
                                && d.CodeId == null)
                            .ToListAsync();

                        var updateList = new List<SysUserRole>();
                        var addList = new List<SysUserRole>();

                        foreach (var storeId in toBindStores)
                        {
                            if (freeRows.Count > 0)
                            {
                                var row = freeRows[0];
                                freeRows.RemoveAt(0);
                                row.StoreId = storeId;
                                row.LastModificationTime = DateTime.Now;
                                row.LastModifierId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
                                updateList.Add(row);
                            }
                            else
                            {
                                addList.Add(new SysUserRole
                                {
                                    Id = Config.GUID(),
                                    UserId = userRole.UserId,
                                    RoleId = userRole.RoleId,
                                    MerchantId = userRole.MerchantId,
                                    StoreId = storeId,
                                    CodeId = null,
                                    // 新增记录先用当前 userRole.Name，占位；昵称统一在最后全量同步
                                    Name = userRole.Name,
                                    CreationTime = DateTime.Now,
                                    CreatorId = _httpContextAccessor.HttpContext?.GetCurrentUserId(),
                                    IsDeleted = false,
                                    EnableStatus = 1,
                                });
                            }
                        }

                        if (updateList.Count > 0)
                        {
                            await _orgIOC._sysUserRoleEFCore.UpdateRangeAsync(updateList);
                            affected += await _orgIOC._sysUserRoleEFCore.SaveChangesAsync();
                        }
                        if (addList.Count > 0)
                        {
                            await _orgIOC._sysUserRoleEFCore.AddRangeAsync(addList);
                            affected += await _orgIOC._sysUserRoleEFCore.SaveChangesAsync();
                        }
                    }
                }
                // 收银员：支持多收款码绑定
                else if (roleType == 6)
                {
                    // 目标收款码集合：优先使用列表，未传列表则回退单值
                    var targetCodeIds = (dto.CodeIds ?? new List<string>()).Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList();
                    if (targetCodeIds.Count == 0 && !string.IsNullOrWhiteSpace(dto.CodeId))
                        targetCodeIds = new List<string> { dto.CodeId };

                    // 当前该成员在此商户下、同角色的“收款码绑定”
                    var currentCodeRows = await _orgIOC._sysUserRoleEFCore.QueryAll(d =>
                            d.MerchantId == userRole.MerchantId
                            && d.UserId == userRole.UserId
                            && d.RoleId == userRole.RoleId
                            && d.CodeId != null)
                        .ToListAsync();
                    var currentCodeIds = currentCodeRows.Select(d => d.CodeId!).Distinct().ToList();

                    var toUnbindCodes = currentCodeIds.Except(targetCodeIds).ToList();
                    var toBindCodes = targetCodeIds.Except(currentCodeIds).ToList();

                    // 解绑：仅清空 CodeId，保留 StoreId（不再分散设置 Name）
                    if (toUnbindCodes.Count > 0)
                    {
                        var unbindList = currentCodeRows.Where(d => toUnbindCodes.Contains(d.CodeId!)).ToList();
                        foreach (var ur in unbindList)
                        {
                            ur.CodeId = null;
                            ur.LastModificationTime = DateTime.Now;
                            ur.LastModifierId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
                        }
                        if (unbindList.Count > 0)
                        {
                            await _orgIOC._sysUserRoleEFCore.UpdateRangeAsync(unbindList);
                            affected += await _orgIOC._sysUserRoleEFCore.SaveChangesAsync();
                        }
                    }

                    // 绑定：确保绑定时 StoreId 与收款码一致；优先复用空闲记录（CodeId==null），不够则新增
                    if (toBindCodes.Count > 0)
                    {
                        // 读取目标收款码信息并校验商户一致性
                        var codeList = await _orgIOC._paymentCodeEFCore.QueryAll(d =>
                                toBindCodes.Contains(d.Id) && d.MerchantId == userRole.MerchantId)
                            .Select(d => new { d.Id, d.StoreId, d.MerchantId })
                            .ToListAsync();

                        if (codeList.Count != toBindCodes.Count)
                            return GetResult(message: "存在无效或跨商户的收款码，无法绑定");

                        // 可复用的空闲记录（未绑定Code）
                        var freeRows = await _orgIOC._sysUserRoleEFCore.QueryAll(d =>
                                d.MerchantId == userRole.MerchantId
                                && d.UserId == userRole.UserId
                                && d.RoleId == userRole.RoleId
                                && d.CodeId == null)
                            .ToListAsync();

                        var updateList = new List<SysUserRole>();
                        var addList = new List<SysUserRole>();

                        foreach (var code in codeList)
                        {
                            SysUserRole? reusable = freeRows.FirstOrDefault(r => r.StoreId == code.StoreId) ?? freeRows.FirstOrDefault();
                            if (reusable != null)
                            {
                                freeRows.Remove(reusable);
                                reusable.StoreId = code.StoreId;   // 对齐门店
                                reusable.CodeId = code.Id;
                                reusable.LastModificationTime = DateTime.Now;
                                reusable.LastModifierId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
                                updateList.Add(reusable);
                            }
                            else
                            {
                                addList.Add(new SysUserRole
                                {
                                    Id = Config.GUID(),
                                    UserId = userRole.UserId,
                                    RoleId = userRole.RoleId,
                                    MerchantId = userRole.MerchantId,
                                    StoreId = code.StoreId,
                                    CodeId = code.Id,
                                    // 新增记录先用当前 userRole.Name，占位；昵称统一在最后全量同步
                                    Name = userRole.Name,
                                    CreationTime = DateTime.Now,
                                    CreatorId = _httpContextAccessor.HttpContext?.GetCurrentUserId(),
                                    IsDeleted = false,
                                    EnableStatus = 1,
                                });
                            }
                        }

                        if (updateList.Count > 0)
                        {
                            await _orgIOC._sysUserRoleEFCore.UpdateRangeAsync(updateList);
                            affected += await _orgIOC._sysUserRoleEFCore.SaveChangesAsync();
                        }
                        if (addList.Count > 0)
                        {
                            await _orgIOC._sysUserRoleEFCore.AddRangeAsync(addList);
                            affected += await _orgIOC._sysUserRoleEFCore.SaveChangesAsync();
                        }
                    }
                }

                // 基本信息“全量同步”：将昵称（Name）同步到该商户下该成员的所有记录，保证一致性
                if (!string.IsNullOrWhiteSpace(dto.Name))
                {
                    var allMemberRows = await _orgIOC._sysUserRoleEFCore.QueryAll(d =>
                            d.MerchantId == userRole.MerchantId
                            && d.UserId == userRole.UserId
                            && d.Name != dto.Name)
                        .ToListAsync();

                    foreach (var row in allMemberRows)
                    {
                        row.Name = dto.Name!;
                        row.LastModificationTime = DateTime.Now;
                        row.LastModifierId = _httpContextAccessor.HttpContext?.GetCurrentUserId();
                    }

                    if (allMemberRows.Count > 0)
                    {
                        await _orgIOC._sysUserRoleEFCore.UpdateRangeAsync(allMemberRows);
                        affected += await _orgIOC._sysUserRoleEFCore.SaveChangesAsync();
                    }
                }

                if (affected == 0)
                    return GetResult(message: "未产生任何变更");

                scope.Complete();
                return GetResult(affected);
            }
            catch (Exception)
            {
                throw;
            }
        }
        
        /// <summary>
        /// 删除团队成员
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> DeleteTeamMembersAsync(DeleteUserRoleRequestDto dto)
        {
            try
            {
                using var scope = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromMinutes(2), TransactionScopeAsyncFlowOption.Enabled);

                var userRole = await _orgIOC._sysUserRoleEFCore.QueryAll(d => d.Id == dto.Id).FirstOrDefaultAsync();
                if (userRole == null)
                    return GetResult(message: "未找到该团队成员信息，请稍后重试！");

                // 一个“团队成员”= 同一用户在同一商户（且同一角色）的所有记录
                var allRows = await _orgIOC._sysUserRoleEFCore.QueryAll(d =>
                        d.MerchantId == userRole.MerchantId
                        && d.UserId == userRole.UserId
                        && d.RoleId == userRole.RoleId)
                    .ToListAsync();

                if (allRows.Count == 0)
                    return GetResult(message: "未找到该团队成员信息，请稍后重试！");

                await _orgIOC._sysUserRoleEFCore.DeleteRangeAsync(allRows);
                var result = await _orgIOC._sysUserRoleEFCore.SaveChangesAsync();

                if (result == 0)
                    return GetResult(message: "删除团队成员失败，请稍后重试！");

                scope.Complete();
                return GetResult(result);
            }
            catch (Exception)
            {
                throw;
            }
        }

    }
}
